#!/usr/bin/perl
# IBM_PROLOG_BEGIN_TAG 
# This is an automatically generated prolog. 
#  
#  
#  
# Licensed Materials - Property of IBM 
#  
# (C) COPYRIGHT International Business Machines Corp. 2002 
# All Rights Reserved 
#  
# US Government Users Restricted Rights - Use, duplication or 
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp. 
#  
# IBM_PROLOG_END_TAG 

use strict;
use POSIX qw(strftime);      # This is to format the time correctly


#/******************************************************************/
# local and global variables
#/******************************************************************/

$::severity = 0;             # we initialize severity to 0, meaning its "info" not an error.
$::SYSTIME  = 0;
my ($host, $ip,$line,$oid,$val,$msg,$trapOID,$rc);    # local variables
my %ERRM = ( "errmCondSeverity"   => "",   # hash with errm values
 	     "errmType"           => "",   # that will be passed in
	     "errmCondName"       => "",   # if this is an errmEvent
	     "errmNodeName"       => "",   # trap.
             "errmRsrcName"       => "",
             "errmRsrcClassName"  => "",
             "errmAttrName"       => "",
             "errmDataType"       => "",
             "errmValue"          => "",
             #"errmMessage"        => ""
            );

#/******************************************************************/
# function: addrec will format a message to be sent to the 
# AuditLog.  It will take in one arg: The message that will be sent.
# Then it will add the message to the audit log.  It will return 
# the return code of the call. 
#/******************************************************************/

sub addrec{
    my $msg = shift;
    if($::ERRMEVENT){
	

    }
    # my $resourceHandle =
    chomp(my $hostname = `/bin/hostname`);
    my $cmd =  "/usr/sbin/rsct/bin/runact-api ";  # build runact-api command 
    $cmd .= "-o IBM.AuditLog::SNMP"; # run this on the IBM.AuditLog resource class
    $cmd .= "::$hostname";     # run this on the local host 
    $cmd .= "::AddRecord";     # the action is to add a record
    $cmd .= "::Time::$::SYSTIME";       # Give this a valid time
    $cmd .= "::Category::$::severity";  # how severe is it?
    $cmd .= "::TemplateId::0";          # SNMP templatae id is 0
    $cmd .= "::SourceNode::$hostname";             # append the hostname
    $cmd .= "::'(CT_CHAR_PTR)'::\"$msg\"";         # append the message
    my $rc = system("$cmd");                       # execute command
    $rc = $rc >> 8;                                # get the return code
    return $rc;          			   # return the exit value

}




#/******************************************************************/
#
# MAIN -- Start of program
#
#/******************************************************************/

if($::ARGV[0] eq "errmEvent"){  # check if this is an errmEvent trap
    $::ERRMEVENT="true";        # if this is an errmevent flag it.
}


# The host and ip address are passed in by snmptrapd via
# STDIN.  These are the first arguments of any trap.



chomp($host = <STDIN>);      # get host name
chomp($ip   = <STDIN>);      # get ip address


# Get the Time value set to local time.

$line = <STDIN>;         # read a line from STDIN
			 # we don't do anything with this value now.

$::SYSTIME = strftime("%s", localtime());  # get the local time.
$::SYSTIME .= "000000"; # multiply seconds to make microseconds.



# The next line received is always the trap id.
# This will tell what type of trap has been received.

$line = <STDIN>;         # read a line from STDIN
($oid,$val) = split(' ',$line);  

# todo: We only support SNMP version 2 traps this is a place
# we can check for that.  We can see if this is an snmp 
# trap by seeing that the OID is:
# .iso.org.dod.internet.snmpV2.snmpModules.snmpMIB.snmpMIBObjects.snmpTrap.snmpTrapOID.0

$trapOID = $val;

# todo: We should also check that if $::ERRMEVENT is set then 
# this trapOID is:
# enterprises.ibm.ibmProd.ibmRSCT.rsctNotifications.errmEvent

if($::ERRMEVENT){


    # make sure that this trap did not come from the localhost:
    # get all the possible local ip addresses:
    my $cmd = "/sbin/ifconfig | /bin/grep inet | /bin/awk '{print \$2}'";
    chomp(my @inets = `$cmd`);
    if($? >> 8){
	print "ERROR RUNNING: $cmd";
	exit 1;
    }

    # push and split ips out of the line.  Then put them in the @ip array.
    my @ips;
    foreach(@inets){
	push @ips, (split(':', $_))[1]; 
    }
    foreach(@ips){
	if($ip eq $_){
	    #print "$ip is equal to $_.\n";
	    exit 0;              # exit if this came from ourselves.
        }
    }
    
 
    while(($line = <STDIN>)){              # read a line of stdin
       	($oid, $val) = split(' ', $line);  # Separate the line into OID and value
        my @oidParts = split /\./,$oid;    # Split the OID's by the .
	my $varBind = $oidParts[$#oidParts]; # The last part is the varbind
	my $match = 0;
	foreach(keys %ERRM){               # make sure that each varbind received
	    if($varBind eq $_){            # is a value in the ERRM hash table.
		$match = "true";
		$ERRM{$_} = $val;
	        last;
 	    }
	}
	unless($match){                    # if there was no match, then we exit.
	  exit 1;
  	}        
    }

    # We need to check that all the variables were
    # defined in the hash:
    foreach (keys %ERRM){
	if($ERRM{$_}){
	  print "$_ is defined as: $ERRM{$_}\n";
  	}else{
	  print "$_ is not defined : $ERRM{$_}\n";
	  exit 1;  # just exit, if not all the variables
		   # were defined, then we just forgetaboutit.

	}
    }
    
    # if the severity is severe, we should make that
    # known:
    if($ERRM{"errmCondSeverity"} eq "Critical"){
	$::severity = 1;
    }
	 
    # get the message that will go to the 
    # auditlog ready

    $msg = "ERRM Trap from $host ($ip)"; # print to AuditLog
    $msg .= "severity: $ERRM{errmCondSeverity}\n";
    $msg .= "type:  $ERRM{errmType}\n";	
    $msg .= "condition: $ERRM{errmCondName}\n";
    $msg .= "resource: $ERRM{errmRsrcName}\n";
    $msg .= "resource class: $ERRM{errmRsrcClassName}\n";
    $msg .= "node: $ERRM{errmNodeName}";
   
    $rc = &addrec($msg);


}else{  # This command is for all other SNMP traps received.


    $msg = "SNMP Trap from $host ($ip)\n"; # print to AuditLog
    $msg .= "Trap Type: $trapOID\n";
    # The other OID's are left to be fed in from snmptrapd via
    # STDIN.  We take all of these and put them in the AuditLog

    while(($line = <STDIN>)){
    	($oid, $val) = split(' ', $line);
    	$msg .= "OID: $oid VALUE: $val\n";
    }

    $rc = &addrec($msg);
}


exit $rc;
